import React, {useState, useEffect, useMemo} from 'react';
import {Button, Checkbox, Flex, message, Select, Space} from "antd";
import './style/style.less';
import { apiRoleList, apiRoleToMenu, apiRoleMenuByRoleId,apiRoleWithIdent } from "@/api/system/role.js";
import { getTreeData } from "@/utils/getTreeData"
import {Logger} from "sass";
import _ from "lodash";

const Index = (props) => {
    const [roleList,setRoleList] = useState([]);
    const [storeRoleId,setStoreRoleId] = useState();
    const [menuList,setMenuList] = useState([]);
    const [indentList,setIndentList] = useState([]);
    const [checkList,setCheckList] = useState([]);
    const [loading,setLoading] = useState(false);

    useEffect(()=>{
        getRoleList()
    },[])
    useEffect(()=>{
        if (storeRoleId){
            getRoleMenuBystoreRoleId()
        }
    },[storeRoleId])

    useEffect(()=>{
        getMenus()
    },[checkList])

    /**
     * @desc 获取角色列表
     * */
    const getRoleList = () => {
        apiRoleList({ pageNo: 1, pageSize: 1000, status: 'Y' }).then(res=>{
            if (res.code === 0 && res.data) {
                if (res.data.length > 0) {
                    const data = res.data.map(v => {
                        return {
                            label: v.roleName === 'STORE' ? '门店管理员' : v.roleName,
                            value: v.storeRoleId
                        }
                    })
                    setRoleList(data)
                    setStoreRoleId(data[0].value)
                }
            }
        })
    }
    /**
     * @desc 获取角色关联菜单
     * */
    const getRoleMenuBystoreRoleId = async () => {
        // const res = await apiRoleMenuByRoleId({ storeRoleId: storeRoleId });
        //
        // this.getMenus()
        // // todo 待后台修改完数据结构后打开
        // this.setState({
        //     checkList: res.data.menus.map(v => v.storeMenuId),
        //     indentList: res.data.idents.map(v => v.storeIdentId)
        // }, () => {
        //     this.getMenus()
        // })

        apiRoleMenuByRoleId({ storeRoleId: storeRoleId }).then(async (res)=>{
            if (res.code === 0) {
                setIndentList(res.data.idents.map(v => v.storeIdentId));
                setCheckList(res.data.menus.map(v => v.storeMenuId));
            }
        })
    }
    /**
     * @desc 获取菜单信息
     * */
    const getMenus = () => {
        apiRoleWithIdent().then(res => {
            if (res.code === 0) {
                setMenuList(getTreeData(setCheckData(res.data)))
            }
        })
    }
    /**
     * @desc 根据角色返回值设置菜单数据
     * @params data {Array} 需要遍历的数组
     * @return Array 返回一个重组后的数组
     * */
    const setCheckData = (data) => {
        const checkL = [...checkList];
        const indentL = [...indentList];
        const result = data.map(v => {
            v.storeIdentId = v.storeMenuId;
            v.key = v.storeMenuId;
            v.isChecked = checkL.includes(v.storeIdentId);
            if (v.sysStoreIdentList.length > 0) {
                v.sysStoreIdentList.map(m => {
                    m.key = m.storeIdentId;
                    m.isChecked = indentL.includes(m.storeIdentId);
                    m.menuName = m.identName
                    return m
                })
            }
            return v
        })
        return result
    }
    /**
     * @desc 顶部角色选择事件
     * */
    const onChange = (e) => {
        setStoreRoleId(e)
    }
    // Filter `option.label` match the user type `input`
    const filterOption = (input, option) =>
        (option?.label ?? '').toLowerCase().includes(input.toLowerCase());
    /**
     * @desc 一级权限选中事件
     * @params number {i} 修改的索引
     * */
    const changeOneLevel = (e, i) => {
        const menuL = [...menuList];
        menuL[i].isChecked = !menuL[i].isChecked;
        if (menuL[i].children && menuL[i].children.length > 0) {
            menuL[i].children.forEach(v => {
                v.isChecked = menuL[i].isChecked;
                v.sysStoreIdentList.forEach(m => {
                    m.isChecked = menuL[i].isChecked;
                })
            })
        }
        setMenuList(menuL)
    }
    /**
     * @desc 二级权限选中事件
     * @params number {i} 一级修改的索引
     * @params number {n} 二级修改的索引
     * */
    const changeTwoLevel = (e, i, n) => {
        const menuL = [...menuList];
        const indentL = [...indentList];
        menuL[i].children[n].isChecked = !menuL[i].children[n].isChecked;
        if (menuL[i].children[n].isChecked) {
            menuL[i].isChecked = true;
        }
        if (menuL[i].children[n].sysStoreIdentList.length > 0) {
            menuL[i].children[n].sysStoreIdentList.forEach(v => {
                indentL.push(v.storeIdentId);
                v.isChecked = menuL[i].children[n].isChecked;
            })
        }
        setMenuList(menuL)
        setIndentList(indentL)
    }
    /**
     * @desc 三级权限选中事件
     * @params number {i} 一级修改的索引
     * @params number {n} 二级修改的索引
     * @params number {j} 三级修改的索引
     * */
    const changeThrLevel = (e, i, n, j) => {
        const menuL = [...menuList];
        let indentL = [...indentList];
        menuL[i].children[n].sysStoreIdentList[j].isChecked = !menuL[i].children[n].sysStoreIdentList[j].isChecked;
        if (menuL[i].children[n].sysStoreIdentList[j].isChecked) {
            indentL.push(menuL[i].children[n].sysStoreIdentList[j].storeIdentId);
        } else {
            indentL = indentL.filter(v => v !== menuL[i].children[n].sysStoreIdentList[j].storeIdentId);
        }
        if (menuL[i].children[n].sysStoreIdentList[j].isChecked) {
            menuL[i].isChecked = true;
            menuL[i].children[n].isChecked = true;
        }
        setMenuList(menuL)
        setIndentList(indentL)
        // this.setState({ menuList, indentList })
    }
    /***
     * @desc 递归获取数据
     *
     * */
    const recursiveData = (arr, data) => {
        let result = data || [];
        if (!Array.isArray(arr)) return;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].isChecked) {
                result.push(arr[i].storeIdentId)
            }
            if (arr[i].children) {
                result = recursiveData(arr[i].children, result)
            }
        }
        return result
    }
    /**
     * @desc 权限保存事件
     * */
   const save = () => {
        // this.setState({ loading: true })
        setLoading(true)
        let storeMenuIds = recursiveData(menuList)
        let indentIds = _.flattenDeep(menuList.map(v => {
            if (v.children) {
                return v.children.map(item => {
                    return item.sysStoreIdentList.filter(value => {
                        return value.isChecked
                    })
                })
            } else {
                return []
            }
        }))
        indentIds = indentIds.length ? indentIds.map(v => v.storeIdentId) : [];

        if (!storeRoleId) {
            setLoading(false)
            return message.error('请选择角色')
        }
        if (storeMenuIds.length <= 0) {
            setLoading(false);
            return message.error('请选择菜单权限')
        }

        apiRoleToMenu({
            storeRoleId: storeRoleId,
            storeMenuIds: storeMenuIds,
            storeIdentIds: indentIds
        }).then(res => {
            if (res.code === 0) {
                message.success('保存成功');
                getRoleMenuBystoreRoleId()
            }
            setLoading(false);
        }).catch(e => {
            setLoading(false);
        })
    }
    return <div className={'wrap-box'}>
        <Space>
            <span>选择角色：</span>
            <Select
                showSearch
                placeholder="请选择用户"
                optionFilterProp="children"
                onChange={onChange}
                filterOption={filterOption}
                value={storeRoleId}
                options={roleList}
            />
        </Space>
        <div className={'wrap-box-content'}>
            <div className='auth-tree-wrap'>
                {
                    menuList.map((v, i) => {
                        return <div className='auth-tree-box' key={i}>
                            <div className='auth-tree-top'>
                                <Checkbox
                                    onChange={(e) => changeOneLevel(e, i)}
                                    checked={v.isChecked} />
                                <em>{v.menuName}</em>
                            </div>
                            <div className='auth-tree-oneLevel'>
                                <ul className='auth-tree-children auth-tree-children'>
                                    {
                                        v.children && v.children.length > 0 && v.children.map((m, n) => {
                                            return <li key={m.storeMenuId}>
                                                <div>
                                                    <Checkbox
                                                        onChange={(e) => changeTwoLevel(e, i, n)}
                                                        checked={m.isChecked} />
                                                    <em>{m.menuName}</em>
                                                </div>

                                                <ul className='auth-tree-children auth-tree-children2'>
                                                    {
                                                        m.sysStoreIdentList && m.sysStoreIdentList.length > 0 && m.sysStoreIdentList.map((k, j) => {
                                                            return <li key={k.storeIdentId}>
                                                                <Checkbox
                                                                    onChange={(e) => changeThrLevel(e, i, n, j)}
                                                                    checked={k.isChecked} />
                                                                <em>{k.identName}</em>
                                                            </li>
                                                        })
                                                    }
                                                </ul>
                                            </li>
                                        })
                                    }
                                </ul>
                            </div>
                        </div>
                    })
                }
            </div>
        </div>
        <Flex justify={'center'} align={'center'} gap={'middle'} >
            <Button type={'primary'} loading={loading} onClick={save}>保存</Button>
        </Flex>
    </div>
};

export default Index;
